package com.newsvoice.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SplashActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);

		SharedPreferences settings = getSharedPreferences(
				NewsVoiceApplication.filePrefrences, MODE_PRIVATE);
		if (settings.getBoolean("myFirstTime", true) || settings.getString("id", "no id").equals("no id")) {
			Log.d("first", "true");
			RegisterUser register = new RegisterUser();
			register.execute();
		}
		Log.d("id", settings.getString("id", "no id"));

		startAnimating();

	}

	/**
	 * Helper method to start the animation on the splash screen
	 */
	private void startAnimating() {
		// Fade in top title
		TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);
		Animation fade1 = AnimationUtils.loadAnimation(this, R.anim.fade_in);
		logo1.startAnimation(fade1);
		// Fade in bottom title after a built-in delay.
		TextView logo2 = (TextView) findViewById(R.id.TextViewBottomTitle);
		Animation fade2 = AnimationUtils.loadAnimation(this, R.anim.fade_in2);
		logo2.startAnimation(fade2);
		// Transition to Main Menu when bottom title finishes animating
		fade2.setAnimationListener(new AnimationListener() {
			public void onAnimationEnd(Animation animation) {
				// The animation has ended, transition to the Main Menu screen
				startActivity(new Intent(SplashActivity.this,
						HomeActivity.class));
				SplashActivity.this.finish();
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationStart(Animation animation) {
			}
		});
		// Load animations for all views within the TableLayout
		Animation spinin = AnimationUtils.loadAnimation(this,
				R.anim.custom_anim);
		LayoutAnimationController controller = new LayoutAnimationController(
				spinin);
		TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
		for (int i = 0; i < table.getChildCount(); i++) {
			TableRow row = (TableRow) table.getChildAt(i);
			row.setLayoutAnimation(controller);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Stop the animation
		TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);
		logo1.clearAnimation();
		TextView logo2 = (TextView) findViewById(R.id.TextViewBottomTitle);
		logo2.clearAnimation();
		TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
		for (int i = 0; i < table.getChildCount(); i++) {
			TableRow row = (TableRow) table.getChildAt(i);
			row.clearAnimation();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		// Start animating at the beginning so we get the full splash screen
		// experience
		startAnimating();
	}



	private class RegisterUser extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			String getUrl = "http://192.168.5.1:8080/VoiceNewsServer/rest/services/register?username=";
			Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
			Account[] accounts = AccountManager.get(getApplicationContext()).getAccounts();
			for (Account account : accounts) {
			    if (emailPattern.matcher(account.name).matches()) {
			        String possibleEmail = account.name;
			        getUrl = getUrl + possibleEmail;
			        break;
			    }
			}
			System.out.println(getUrl);
			HttpGet httpGet = new HttpGet(getUrl);
			HttpResponse response;
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String ret = null;
			try {
				response = httpClient.execute(httpGet);
				ret = EntityUtils.toString(response.getEntity());

			} catch (Exception e) {
				if (e != null && e.getMessage() != null)
					Log.e("splash", e.getMessage());
				else if (e != null)
					Log.e("splash", e.toString());
				else
					Log.e("splash", "NULL Exception");
			}

			// we assume that the response body contains the error message

			return ret;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			SharedPreferences setting = getSharedPreferences(NewsVoiceApplication.filePrefrences, MODE_PRIVATE);
			Editor editor = setting.edit();
			editor.putBoolean("myFirstTime", false);
			editor.putString("id", result);
			editor.commit();
			System.out.println(result);
		}

	}
}
